package com.wolfking.demo;

import java.util.concurrent.FutureTask;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;

public class FutureTaskDemo {
    public static void main(String[] args) throws Exception{

        FutureTask<Long> task = new FutureTask<>(() -> {
            try {
                TimeUnit.SECONDS.sleep(5);
                System.out.println("end");
                return 1L;
            } catch (InterruptedException e) {
                System.out.println("ex");
                e.printStackTrace();
            }
            return -1L;
        });

        Thread thread = new Thread(task);
        thread.start();

       try{
           System.out.println(task.get(1,TimeUnit.SECONDS));
       }catch (TimeoutException e){
           System.out.println("timeout");
           task.cancel(false);
       }
    }
}
